#include "QcGroupedListView.h"
#include <QHoverEvent>

QcGroupedListView::QcGroupedListView(QWidget *parent)
    : QListView{parent}
{

}

// 参考QTreeView::viewportEvent实现，更新branch的hover状态
bool QcGroupedListView::viewportEvent(QEvent *event)
{
    switch (event->type()) {
    case QEvent::HoverEnter:
    case QEvent::HoverLeave:
    case QEvent::HoverMove: {
        QHoverEvent *he = static_cast<QHoverEvent*>(event);
        const int oldBranch = hoverBranch_;
        hoverBranch_ = branchAt_(he->position().toPoint());
        if (hoverBranch_ != oldBranch) {
            // Update the whole hovered over row. No need to update the old hovered
            // row, that is taken care in superclass hover handling.
            viewport()->update(visualRect(indexAt(he->position().toPoint())));
        }
        break; }
    default:
        break;
    }

    return QListView::viewportEvent(event);
}


int QcGroupedListView::branchAt_(const QPoint& pt) const
{
    auto index = this->indexAt(pt);
    if (index.isValid() && model()->hasChildren(index)) {
        auto rc = branchRect_(index.row());
        if (rc.contains(pt))
            return index.row();
    }

    return -1;
}

QRect QcGroupedListView::branchRect_(int row) const
{
    auto rc = visualRect(model()->index(row, 0));
    rc.setWidth(branchWidth_);
    return rc;
}

// 用户点击branch时，展开/收缩分组项目
void QcGroupedListView::mousePressEvent(QMouseEvent *event)
{
    if (hoverBranch_ >= 0) {
        emit toggleExpandedState(model()->index(hoverBranch_, 0));
    }

    return QListView::mousePressEvent(event);
}
